package model;

import java.io.*;
import java.util.ArrayList;

/**
 *
 * @author Sacha MASSON
 */
public class WriteToCSV {

    //European countries use ";" as 
    //CSV separator because "," is their digit separator
    private static final String CSV_SEPARATOR = ",";

    public static void csvwrite(ArrayList<Contact> contactList) {
        try {
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream("contactlist.csv"), "UTF-8"));
            for (Contact contactlist : contactList) {
                StringBuilder oneLine = new StringBuilder();

                oneLine.append(contactlist.getName().trim().length() == 0 ? "" : contactlist.getName());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getFirstName().trim().length() == 0 ? "" : contactlist.getFirstName());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getHomeAddress().trim().length() == 0 ? "" : contactlist.getHomeAddress());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getProfessionalPhone().trim().length() == 0 ? "" : contactlist.getProfessionalPhone());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getPersonalPhone().trim().length() == 0 ? "" : contactlist.getPersonalPhone());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getHomePage().trim().length() == 0 ? "" : contactlist.getHomePage());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getEmail().trim().length() == 0 ? "" : contactlist.getEmail());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getOther().trim().length() == 0 ? "" : contactlist.getOther());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getImage().trim().length() == 0 ? "" : contactlist.getImage());
                oneLine.append(CSV_SEPARATOR);
                oneLine.append(contactlist.getGroup());
                bw.write(oneLine.toString());
                bw.newLine();
            }
            bw.flush();
            bw.close();
        } catch (UnsupportedEncodingException e) {
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
    }
}
